import {Loading} from "element-ui";
import {message} from '@common/assets/js/resetMessage';
import utils from "@common/utils/utils";

const picTypeList = ['bmp', 'jpg', 'png', 'gif', 'jpeg', 'svg', 'psd', 'tiff', 'webp', 'eps'];

const batchPrintFile = (GSCloudPlugin, list, size, index, success) => {
	if (!index) {
		index = 0;
	}
	let currItem = list[index];
	print.hideLoading();
	print.showLoading(`正在打印${currItem.name || ''}.....`);
	print.printFile(GSCloudPlugin, currItem.url, currItem.name, size).then(() => {
		if (index + 1 <= list.length - 1) {
			batchPrintFile(GSCloudPlugin, list, size, index + 1);
		} else {
			print.hideLoading();
		}
	}).catch(err => {
		if (err.Code === 201) {
			message.info(err.Message);
		} else {
			message.error(err.Message);
		}
		if (index + 1 <= list.length - 1) {
			batchPrintFile(GSCloudPlugin, list, size, index + 1);
		} else {
			print.hideLoading();
			typeof success === 'function' && success();
		}
	});
};

const getOrientation = size => {
	if (utils.isNotEmpty(size)) {
		if (size === 'portrait') {
			return 'Portrait';
		}
		if (size === 'landscape') {
			return 'Landscape';
		}
	}
	return 'Auto';
};

const print = {
	loading: undefined,
	showLoading (text) {
		print.loading = Loading.service({
			lock: true,
			text: text,
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.5)',
			customClass: 'tsd_loading',
		});
	},
	hideLoading () {
		if (print.loading) {
			print.loading.close();
		}
	},
	printFile (GSCloudPlugin, url, fileName, size) {
		let startIndex = fileName.lastIndexOf(".");
		let fileType = fileName.substring(startIndex + 1, fileName.length).toLowerCase();
		if (fileType === 'pdf') {
			return print.printPdf(GSCloudPlugin, url, fileName, size);
		} else if (fileType === 'doc' || fileType === 'docx') {
			return print.printWord(GSCloudPlugin, url, fileName, size);
		} else if (fileType === 'htm' || fileType === 'html') {
			if (url.indexOf('<') !== -1 && url.indexOf('>') !== -1) {
				return print.printDraw4Html(GSCloudPlugin, url, fileName, size);
			}
			if (url.indexOf('http') === 0) {
				return print.printHtml4Url(GSCloudPlugin, url, fileName, size);
			}
			return print.printHtml(GSCloudPlugin, url, fileName, size);
		} else if (picTypeList.indexOf(fileType) !== -1) {
			return print.printImage(GSCloudPlugin, url, fileName, size);
		}
		return new Promise((resolve, reject) => {
			reject({Code: 500, Message: '不支持的文件类型'});
		});
	},
	printFile4List(GSCloudPlugin, list, urlField, nameField, size) {
		return new Promise(resolve => {
			if (list && list.length > 0) {
				let mapList = list.map(item => {
					return {
						url: item[urlField],
						name: item[nameField],
					};
				});
				batchPrintFile(GSCloudPlugin, mapList, size, 0, () => {
					resolve();
				});
			}
		});
	},
	printPdf (GSCloudPlugin, url, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintPdf({
				Title: fileName, //标题 - String - 默认GUID格式字符串
				Width: 210,//纸张宽度。单位毫米 - Int - 0
				Height: 297,//纸张高度。单位毫米；值为0时，打印高度自适应，应用于连续纸张 - Int - 0
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				Url: url,//PDF文件地址 - String - 无
				PrinterName: GSCloudPlugin.PrinterName || '',//打印机名称。不传值则使用默认打印机 - String - 无
				UseFileCache: false,//适用于大文件。需要先调用下载文件或异步下载文件，注意：并且需要设置Title一致 - bool - false
				RemoveMargin: false,//移除空白边距。适用于四周有较大的空白边距的不正规PDF文档；当然其他的类型打印也可以使用该参数 - bool - false
				Cookies: [],//cookie - Array - 无
				HttpHeaders: [],//http头信息 - Array - 无
				Copies: 1,//打印文档份数 - Int - 1
				IsAsync: false,//是否异步；如果为true，则每打印完一页，就会回调一次；如果为false，则等到全部页打印完，才回调一次。支持浏览器：谷歌、火狐、IE10+ - bool - false
				Duplex: 'Default',//双面打印 - String - Default（打印机默认的双面打印设置）、Simplex（单面打印）、Vertical（双面垂直打印）、Horizontal（双面水平打印）
				PaperSource: '',//纸张来源 - String - 无
				Orientation: getOrientation(size), // 打印方向；值：Auto(自适应)、Portrait(纵向)、Landscape(横向)；默认：Auto
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
	printWord (GSCloudPlugin, url, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintWord({
				Title: fileName,
				Width: 210,
				Height: 297,
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				Url: url,
				PrinterName: GSCloudPlugin.PrinterName || '',
				IsAsync: false,
				Orientation: getOrientation(size),
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
	printHtml (GSCloudPlugin, Url, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintHtml({
				Title: fileName,
				Width: 210,
				Height: 297,
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				Url: Url,
				PrinterName: GSCloudPlugin.PrinterName || '',
				IsAsync: false,
				Orientation: getOrientation(size),
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
	printImage (GSCloudPlugin, url, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintImage({
				Title: fileName,
				Width: 210,
				Height: 297,
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				Url: url,
				PrinterName: GSCloudPlugin.PrinterName || '',
				IsAsync: false,
				Orientation: getOrientation(size),
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
	printHtml4Url (GSCloudPlugin, Url, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintHtml({
				Title: fileName,
				Width: 210,
				Height: 297,
				Url: Url,
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				PrinterName: GSCloudPlugin.PrinterName || '',
				IsAsync: false,
				Orientation: getOrientation(size),
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
	printDraw4Html (GSCloudPlugin, html, fileName, size) {
		return new Promise((resolve, reject) => {
			GSCloudPlugin.PrintDraw({
				Title: fileName,
				Width: 210,
				Height: 297,
				PaperName: 'A4', // 指定打印纸张名称；如果设置此参数，则Width、Height参数无效
				Htmls: [{
					X: 0,
					Y: 0,
					Width: utils.isNotEmpty(size) ? (size === 'portrait' ? 210 : 297) : 210,
					Height: utils.isNotEmpty(size) ? (size === 'portrait' ? 297 : 210) : 297,
					Url: html,
				}],
				PrintMethod: 'Print',
				PrinterName: GSCloudPlugin.PrinterName || '',
				Orientation: getOrientation(size),
				OnSuccess: function (result) {
					resolve(result);
				},
				OnError: function (result) {
					reject(result);
				}
			});
		});
	},
};

export default print;
